(function(){//String的一些扩展
    /**
     * 字符串去除左右两端的空白字符
     * " sadfsw saf ".trim() 结果为："sadfsw saf"
     */
    String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, '');
    }
})();
/**
 * 公用的一些函数，jquery扩展
 * @charset utf8
 * @autor liujhc
 */
(function($){
    window.console=window.console||{//如果不支持console，就alert
        log:function(){}//window.alert
    };
    //禁用ajax缓存
    $.ajaxSetup({
        cache:false
    });
    $.extend({
        /**
         * 包装函数，支持在函数前后加入其他代码，返回新的函数
         * @param target 要包装的函数
         * @param before 在func执行之前执行的函数
         * @param after 在func执行后执行的函数
         * @return 返回经过包装后的函数，并附带了target原来的属性
         */
        wrap:function(target,before,after){
            return $.extend(function(){
                var result;
                if($.isFunction(before)){
                    before.apply(this,arguments);
                }
                if($.isFunction(target)){
                    result =target.apply(this,arguments);
                }
                if($.isFunction(after)){
                    after.apply(this,arguments);
                }
                return result;
            },target);
        },
        /**
         * 加载js
         */
        loadScript:function(url){
            var scrTag = document.createElement("script");
            scrTag.type="text/javascript";
            scrTag.src=url;
            document.getElementsByTagName("head")[0].appendChild(scrTag);
        },
        /**
		 * 将复杂js对象转换成url参数
		 */
        param: function( a, traditional ) {
            var s = [],
            add = function( key, value ) {
                // If value is a function, invoke it and return its value
                value = jQuery.isFunction( value ) ? value() : value;
                s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value==null?"":value );
            };
            
            // Set traditional to true for jQuery <= 1.3.2 behavior.
            if ( traditional === undefined ) {
                traditional = jQuery.ajaxSettings.traditional;
            }

            // If an array was passed in, assume that it is an array of form elements.
            if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
                // Serialize the form elements
                jQuery.each( a, function() {
                    add( this.name, this.value );
                });

            } else {
                // If traditional, encode the "old" way (the way 1.3.2 or older
                // did it), otherwise encode params recursively.
                for ( var prefix in a ) {
                    buildParams( prefix, a[ prefix ], traditional, add );
                }
            }

            // Return the resulting serialization
            return s.join( "&" ).replace( /%20/g, "+" );
        },
        /**
         * 在构建正则表达式之前，将字符串中的关键字符替换，以免影响正则表达式的含义
         */
        preRegexp:function(str){
            return str.replace(/[\"\'\\\*\+\?\.\,\|\&\^\$\(\)\{\}\[\]]/g,function(c){
                return "\\"+c;
            });
        },
        /**
         * js模板引擎
         * @param template
         * @param data
         */
        template:function(template,data){
            return template.replace(/\${\s?(\w*?)\s?}/igm,function($,$1){
                return  data[$1]||$;
            });
        }
    });
    function buildParams( prefix, obj, traditional, add ) {
        if ( jQuery.isArray( obj ) ) {
            // Serialize array item.
            jQuery.each( obj, function( i, v ) {
                if ( traditional || /\[\]$/.test( prefix ) ) {
                    add( prefix, v );
                } else {
                    buildParams( prefix + ( typeof v === "object" || jQuery.isArray(v) ? "[" + i + "]": "" ) , v, traditional, add );
                }
            });

        } else if ( !traditional && obj != null && typeof obj === "object" ) {
            // Serialize object item.
            for ( var name in obj ) {
                buildParams( prefix + "['" + encodeURIComponent(name) + "']", obj[ name ], traditional, add );
            //buildParams( prefix + "." + name, obj[ name ], traditional, add );
            }
        } else {
            // Serialize scalar item.
            add( prefix, obj );
        }
    }
    /**
	 * jQuery扩展
	 */
    $.fn.extend({
        /**
		 * 自动填充表单,支持类似form.userName这样的属性映射，
		 * 例如：如需填充name='form.userName'的表单元素，传入下面两种结构的json对象都可以准确映射：
		 * {'form.userName':'Tom'}或{form:{userName:"Tom"}}
		 */
        fillForm:function(data){
            if(data && typeof data=="object"){
                this.find(":input:not(:button)").each(function(){
                    var $field=$(this), value = null, key = $field.attr("name");
                    if(data.hasOwnProperty(key)){
                        value = data[key];
                    }else{
                        try{
                            value = eval("data."+key);
                        }catch(e){
                        //console&&console.log(e);
                        }
                    }
                    if(value!=null){
                        if($field.is(":checkbox,:radio")){
                            var feval=$field.attr("value"),checked=$field.is(":checked");
                            $field.removeAttr("checked");
                            if($.isArray(value)){
                                for(var i=0; i<value.length; i++){
                                    if(feval==value[i]){
                                        $field.attr("checked", "checked");
                                        if(!checked){
                                            $field.change();
                                        }
                                    }
                                }
                            }else if(feval==value){
                                $field.attr("checked", "checked");
                                if(!checked){
                                    $field.change();
                                }
                            }
                        }else{
                            $field.val($.isArray(value)?value[0]:value);
                        }
                    }
                });
            }
            return this;
        },
        resetForm:function(){//jQuery.form.js插件的resetForm方法有bug，在此重写
            this.each(function(){
                if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
                    this.reset();
                }
            }).find(":input:not(:button)").each(function(){
                $(this).val($(this).val());
            });
            return this;
        },
        /**
		 * 对于所选元素进行排序
		 * @parent sortby 排序方法
		 * 例如,对select的选项按名称排序:
		 * $("select:eq(0) option").sort(function(a,b){
		 *    var ta=$(a).text(), tb=$(b).text();
		 *    return ta>tb?1:(ta<tb?-1:0);
		 * });
		 */
        sort:function(sortby){
            var $parent = this.parent();
            if(!sortby){//默认用文本排序
                sortby=function(a,b){
                    var ta=$(a).text(), tb=$(b).text();
                    return ta>tb?1:(ta<tb?-1:0);
                }
            }
            $.each(this.get().sort(sortby),function(){
                $parent.append(this);
            })
            return this;
        },
        /**
		 * 获取被选内容中的表单数据
		 */
        formData:function(){
            var result={}, $form=$(this);
            $form.find(":input[name]:not(:button,:checkbox,:radio)").add("input:checked",$form).each(function(){
                var $field=$(this), val=[], name=$field.attr("name");
                if($field.is("select")){
                    $field.find("option[value]:selected").each(function(){
                        val.push($(this).attr("value"));
                    });
                }else{
                    val.push($field.attr("value"));
                }
                result[name] = $.merge(result[name]||[],val);
            });
            return result;
        },
        /**
         * 可输入的下拉列表
         */
        inputSelect:function (options) {
            var defaultOption = {
                option: "input"
            };
            options = $.extend(defaultOption, options);
            this.each(function () {
                var $current = $(this);
                $current.css({
                    "marginLeft": "-150px",
                    "position": "relative"
                }).wrap("<span></span>").wrap("<span></span>");
                var $parent = $current.parent().css({
                    marginLeft:150,
                    overflow:"visible"
                }).parent().css({
                    position: "relative",
                    display: "inline-block",
                    width:$current.width()+3
                });
                var $input = $("<input name='"+($current.attr("name")||"")+"_input' type='text'/>").css({
                    position:"absolute",
                    left:1,
                    top:2,
                    border:"none",
                    display:"none",
                    height:$current.height()-3,
                    width:$current.width() - 20
                });
                $input.appendTo($parent).blur(function(){
                    var val = $(this).val();
                    if(val==""){
                        $input.hide();
                        $current.children(":first").attr("selected","selected");
                    }else{
                        $current.children().each(function(){
                            if($(this).attr("value")!=options.option && $(this).text()==val){
                                $input.hide();
                                $(this).attr("selected","selected");
                                $current.select();
                                return false;
                            }
                        });
                    }
                });
                $current.height($current.height()+3).change(function(){
                    if($current.children("option:selected").attr("value")==options.option){
                        $input.show().select();
                    }else{
                        $input.hide();
                    }
                });
            });
            return this;
        },
        iframeReady:function(callback){
            if(this.is("iframe")){
                var iframe = this[0];
                if (iframe.attachEvent){
                    iframe.attachEvent("onload", function(){
                        callback.call(iframe);
                    });
                } else {
                    iframe.onload = function(){
                        callback.call(iframe)
                    };
                }
            }
            return this;
        }
    });

    $(function(){
        /*
		 * 页面框架的右上角按钮功能
		 */
        $(".frame .frame-head .frame-button.plus").each(function(){
        	$(this).parent().next(".frame-content").hide();
        });
        $(".frame .frame-head .frame-button.plus").live("click",function(){
        	$(this).removeClass("plus")
        	.addClass("minus")
        	.parent().next(".frame-content")
        	.slideDown("normal", function(){$(window).resize();});
       	});
        $(".frame .frame-head .frame-button.minus").live("click",function(){
        	$(this).removeClass("minus")
        	.addClass("plus")
        	.parent().next(".frame-content")
        	.slideUp("normal", function(){$(window).resize();});
       	});

        $(".btn-dialog-cancel").live("click",function(){//当点击对话框中的取消按钮时，关闭该对话框
            $(this).parents(".ui-dialog-content").dialog("close");
        });
        $("select.input-select").inputSelect();
    });
})(jQuery);